<?php

namespace App\Modules\Admin\Services;

use App\Exceptions\ValidationException;
use App\Facades\UniqID;
use App\Modules\Admin\Models\AdminRoleUser;
use App\Modules\Admin\Repositories\Contracts\AdminUserRepository;
use Illuminate\Support\Facades\Hash;

class AdminUserService
{
    private $adminUserRepository;

    public function __construct(AdminUserRepository $adminUserRepository)
    {
        $this->adminUserRepository = $adminUserRepository;
    }

    /**
     * 获取列表
     *
     * @param array|null $param
     */
    public function getList($param = null)
    {
        try {
            $filter = [];
            $result = $this->adminUserRepository->paginate($param['per_page'] ?? null, $filter);

            return $result;
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    /**
     * 获取详情
     *
     * @param int $id
     * @return object|array
     */
    public function getInfo($id)
    {
        try {
            $result = $this->adminUserRepository->find($id);
            return $result;
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    /**
     * 新增
     *
     * @param array $param
     */
    public function add($param)
    {
        try {
            //判断帐号在库里是否存在
            $search = ['account' => $param['account']];
            $adminUser = $this->adminUserRepository->findByFilter($search, ['admin_uid']);
            if (!is_null($adminUser)) {
                throw new ValidationException('帐号已存在');
            }
            $result = \DB::transaction(function () use ($param) {
                $data = [
                    'admin_uid' => UniqID::nextId(),
                    'source_type' => 1,
                    'password' => Hash::make(md5($param['password'])),
                    'account' => $param['account'],
                    'name' => $param['name'] ?? $param['account'],
                    'sex' => $param['sex'] ?? 0,
                ];

                //上传头像
                // if (!empty($param['avatar'])) {
                //     //构建存储的文件夹规则，值如：adminAvatars/adminUid/201903/21/
                //     $moduleName = 'admin_avatars/' . $data['admin_uid'] . '/' . date('Ym', time()) . '/' . date('d', time());
                //     // 将图片移动到我们的目标存储路径中
                //     $storageFile = Storage::putFile($moduleName, $param['avatar']);
                //     $data['avatar'] = Storage::url($storageFile);
                // }

                $adminUser = $this->adminUserRepository->store($data);
                return $adminUser;
            });

            return $result;
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    /**
     * 修改
     *
     * @param array $param
     */
    public function update($param)
    {
        if (isset($param['admin_uid'])) {
            $result = \DB::transaction(function () use ($param) {
                $model = $this->adminUserRepository->findByFilter(['admin_uid' => $param['admin_uid']]);

                if (is_null($model)) {
                    throw new ValidationException('数据不存在');
                }

                //如果有头像替换，先删除旧的，再新增
                // if (!is_null($param['avatar'])) {
                //     if (!is_null($model->avatar)) {
                //         $basePath = Storage::getBasePath($model->avatar);
                //         if (Storage::has($basePath)) {
                //             Storage::delete($basePath);
                //         }
                //     }
                //     //新增新
                //     $moduleName = 'admin_avatars/' . $model->admin_uid . '/' . date('Ym', time()) . '/' . date('d', time());
                //     $storageFile = Storage::putFile($moduleName, $param['avatar']);
                //     $param['avatar'] = Storage::url($storageFile);
                // }

                $num = $this->adminUserRepository->updateByFilter($param, ['admin_uid' => $model->admin_uid]);
                if ($num == 0) {
                    throw new ValidationException('修改失败');
                }
                return $param;
            });
        } else {
            $result = $this->add($param);
        }

        return $result;
    }

    /**
     * 更换密码
     *
     * @param [type] $param
     * @return array
     */
    public function updatePassword($param)
    {
        $adminUser = $this->adminUserRepository->findByFilter(['admin_uid' => $param['admin_uid']]);

        $booleanValue = Hash::check(md5($param['old_password']), $adminUser->password);

        if ($booleanValue) {
            $data = [
                'password' => Hash::make(md5($param['new_password'])),
            ];
            $num = $this->adminUserRepository->updateByFilter($data, ['admin_uid' => $adminUser->admin_uid]);
            if ($num == 0) {
                throw new ValidationException('修改失败');
            }
        } else {
            throw new ValidationException('密码错误');
        }
        return $adminUser;
    }

    public function roleUser($adminUid)
    {
        try {
            
            return;
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    /**
     * 删除
     *
     * @param int $id
     */
    public function delete($id)
    {
        try {
            $adminUser = $this->adminUserRepository->delete($id);

            $result = [];
            if ($adminUser) {
                $result = 'success';
            } else {
                $result = 'error';
            }
            return $result;

        } catch (\Throwable $th) {
            throw $th;
        }
    }
}
